//
//  LYCUserInfoModel.swift
//  新浪微博
//
//  Created by liuyanchi on 16/7/30.
//  Copyright © 2016年 liuyanchi. All rights reserved.
//

import UIKit

class LYCUserInfoModel: NSObject{
    
    
    var access_token: String?
    
    // 定义一个过期的时间变量
    var expires_in:NSTimeInterval = 0 {
    
        didSet{
            
            // 给过去描述赋值的时候,就转变成了时间
        expires_date = NSDate(timeIntervalSinceNow: expires_in)
            
        }
    
      }
    
    var expires_date: NSDate?
    
    var uid: String?
    
    var screen_name: String?
    
    var profile_image_url: String?
    
    init(dict:[String: NSObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    // 归档和解档把对象保存起来
    // 只是告诉控制器以何种方式进行进行解档,解档的具体操作在下面
    // 解档
    required init(coder aDecoder:NSCoder) {
        
        self.access_token = aDecoder.decodeObjectForKey("access_token") as? String
        
        self.expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
        
        self.uid = aDecoder.decodeObjectForKey("uid") as? String
        
        self.screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        
        self.profile_image_url = aDecoder.decodeObjectForKey("aDecoder") as? String
        
        
        // 调用父类
        super.init()
        
    }
    
    // 归档,把对象以二进制的形式保存起来
     // 只是告诉控制器以何种方式进行进行归档,解档的具体操作在下面
    func encodeWithCoder(acoder: NSCoder){
        
        acoder.encodeObject(access_token,forKey: "access_token")
        
        acoder.encodeObject(expires_date, forKey: "expires_date")
        
        acoder.encodeObject(uid, forKey: "uid")
        
        acoder.encodeObject(screen_name, forKey: "screen_name")
        
        acoder.encodeObject(profile_image_url, forKey: "profile_image_url")
        
        
    }
    
    // 定义一个静态变量供类直接调用
    static let userInfoPath = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("aaa.aaa")
    
    
   // MARK:-- 保存到沙河
    func saveModel(){
      
    NSKeyedArchiver.archiveRootObject(self, toFile: LYCUserInfoModel.userInfoPath)
        
        }
    
    
   // MARK:-- 通过类方法,读取数据
    class func readModel()->LYCUserInfoModel? {
        
        let model = NSKeyedUnarchiver.unarchiveObjectWithFile(LYCUserInfoModel.userInfoPath) as? LYCUserInfoModel
        
        
        guard let data = model?.expires_date else{
        
        return nil
    
        }
        
        if data.compare(NSDate()) == .OrderedAscending{
        
        return nil
        
        }else if data.compare(NSDate()) == .OrderedSame{
        return nil
        
        }else{
        
        return model
        
        }
        
    }
    
    
}
